package com.weetop.akly.activity.communicationIndex;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.weetop.akly.R;
import com.weetop.akly.activity.work.AskForLeaveActivity;
import com.weetop.akly.activity.work.EvectionApplyActivity;
import com.weetop.akly.activity.work.OutApplyActivity;
import com.weetop.akly.activity.work.SignOutActivity;
import com.weetop.akly.activity.work.WorkOverTimeActivity;
import com.weetop.akly.appConfig.GlobalConstants;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.base.mvp.BaseObserver;
import com.weetop.akly.base.mvp.BasePresenter;
import com.weetop.akly.bean.MemberBean;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.GlideUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DepartmentActivity extends BaseActivity {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_data_title)
    TextView tvDataTitle;
    @BindView(R.id.rcy_data)
    RecyclerView rcyData;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.et_search)
    EditText etSearch;
    private CommonRecyclerAdapter<MemberBean> adapter;
    private ArrayList<MemberBean> memberList = new ArrayList<>();
    private ArrayList<MemberBean> selectedMembers = new ArrayList<>();
    private String fromModeId;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_department);
        ButterKnife.bind(this);

        int department_id = getIntent().getIntExtra("department_id", -1);
        String keywords = getIntent().getStringExtra("keywords");
        String title = getIntent().getStringExtra("title");
        fromModeId = getIntent().getStringExtra("fromModeId");
        if (!TextUtils.isEmpty(fromModeId)) {
            initSelectList();
            selectedMembers = new ArrayList<>();
            btnConfirm.setVisibility(View.VISIBLE);
        } else {
            initList();
            btnConfirm.setVisibility(View.GONE);
        }
        setTitleInfo(title);
        if (department_id != -1) {
            getMemberList(department_id + "");
        } else if (!TextUtils.isEmpty(keywords)) {
            getMemberListByKeywords(keywords + "");
        }

        initEvent();
    }


    private void initEvent() {
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    performSearch();
                    return true;
                }
                return false;
            }
        });
    }

    private void performSearch() {
        etSearch.clearFocus();
        InputMethodManager in = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
        //...perform search
        String keywords = etSearch.getText().toString().trim();
//        if (!TextUtils.isEmpty(keywords)) {
        getMemberListByKeywords(keywords);
//        }
    }


    private void initList() {
        adapter = new CommonRecyclerAdapter<MemberBean>(mContext, R.layout.item_department_user, memberList) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, MemberBean item, int position) {
                ImageView ivHead = helper.getView(R.id.iv_member_head);
//                GlideUtil.load(mActivity, ivHead, item.getPhoto(), R.mipmap.headimg, R.mipmap.headimg);
                Glide.with(mActivity)
                        .load(item.getPhoto())
                        .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                        .apply(new RequestOptions()
                                .transforms(new CenterCrop(), new RoundedCorners(15))
                                .placeholder(R.mipmap.headimg)//图片加载出来前，显示的图片
                                .fallback(R.mipmap.headimg)
                                .error(R.mipmap.headimg))
                        .into(ivHead);
                helper.setText(R.id.tv_member_name, item.getName());
                helper.setText(R.id.tv_member_account, "人员编号：" + item.getAccount());
                helper.setText(R.id.tv_member_tel, "手机 " + item.getTelephone());
            }
        };
        rcyData.setLayoutManager(new LinearLayoutManager(this));
        rcyData.setAdapter(adapter);
        adapter.setOnItemClickListener((viewHolder, view, position) -> {
            if (BaseUtils.fastClick() && !TextUtils.isEmpty(memberList.get(position).getAccount())) {
                Intent intent = new Intent();
                MemberBean memberBean = memberList.get(position);
                intent.putExtra(GlobalConstants.Account, memberBean.getAccount());
                intent.putExtra(GlobalConstants.Name, memberBean.getName());
                intent.putExtra(GlobalConstants.CompanyTel, memberBean.getCompany_tel());
                intent.putExtra(GlobalConstants.Email, memberBean.getEmail());
                intent.putExtra(GlobalConstants.HeadPhoto, memberBean.getPhoto());
                intent.putExtra(GlobalConstants.Job, memberBean.getJob());
                intent.putExtra(GlobalConstants.Department, memberBean.getDepartment());
                intent.putExtra(GlobalConstants.Telephone, memberBean.getTelephone());
                intent.putExtra(GlobalConstants.TargetId, memberBean.getId());
                BaseUtils.toActivity(mActivity, UserDetailActivity.class, intent);
            }
        });
    }
    ImageView oldView;
    private void initSelectList() {
        adapter = new CommonRecyclerAdapter<MemberBean>(mContext, R.layout.item_department_user, memberList) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, MemberBean item, int position) {
                ImageView ivHead = helper.getView(R.id.iv_member_head);
                helper.setVisible(R.id.iv_arrow, View.GONE);
//                GlideUtil.load(mActivity, ivHead, item.getPhoto(), R.mipmap.headimg, R.mipmap.headimg);
                Glide.with(mActivity)
                        .load(item.getPhoto())
                        .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                        .apply(new RequestOptions()
                                .transforms(new CenterCrop(), new RoundedCorners(15))
                                .placeholder(R.mipmap.headimg)//图片加载出来前，显示的图片
                                .fallback(R.mipmap.headimg)
                                .error(R.mipmap.headimg))
                        .into(ivHead);
                helper.setText(R.id.tv_member_name, item.getName());
                helper.setText(R.id.tv_member_account, "人员编号：" + item.getAccount());
                helper.setText(R.id.tv_member_tel, "手机 " + item.getTelephone());
            }
        };
        rcyData.setLayoutManager(new LinearLayoutManager(this));
        rcyData.setAdapter(adapter);
        adapter.setOnItemClickListener((viewHolder, view, position) -> {
            ImageView ivSelectIcon = (ImageView) view.findViewById(R.id.iv_select_icon);
            MemberBean memberBean = memberList.get(position);
//            if (BaseUtils.fastClick()) {
            if (fromModeId.equals("2")) {
                if(oldView!= null){
                    oldView.setVisibility(View.INVISIBLE);
                }
                ivSelectIcon.setVisibility(View.VISIBLE);
                selectedMembers.clear();
                selectedMembers.add(memberBean);
                oldView = ivSelectIcon;
            } else {
                if (selectedMembers.contains(memberBean)) {
                    ivSelectIcon.setVisibility(View.INVISIBLE);
                    selectedMembers.remove(memberBean);
                } else {
                    ivSelectIcon.setVisibility(View.VISIBLE);
                    selectedMembers.add(memberBean);
                }
            }
//            }
        });
    }

    private void getMemberList(String department_id) {
        selectedMembers.clear();
        addDisposable(apiServer.getMemberList(department_id), new BaseObserver<BaseModel<ArrayList<MemberBean>>>(this) {
            @Override
            public void onSuccess(BaseModel<ArrayList<MemberBean>> o) {
                memberList.clear();
                memberList.addAll(o.getData());
                adapter.replaceAll(memberList);
            }

            @Override
            public void onError(String msg) {
                showError(msg);
            }
        });
    }

    private void getMemberListByKeywords(String keywords) {
        selectedMembers.clear();
        addDisposable(apiServer.searchMembers(keywords), new BaseObserver<BaseModel<ArrayList<MemberBean>>>(this) {
            @Override
            public void onSuccess(BaseModel<ArrayList<MemberBean>> o) {
                memberList.clear();
                memberList.addAll(o.getData());
                adapter.replaceAll(memberList);
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    @OnClick(R.id.btn_confirm)
    public void onViewClicked() {
        if (BaseUtils.fastClick()) {
            Log.e(TAG, "onViewClicked: btn_confirm---" + GsonUtils.toJson(selectedMembers));
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("select_members", GsonUtils.toJson(selectedMembers));
            switch (fromModeId) {
                case "1":
                    BaseUtils.toActivity(this, SignOutActivity.class, intent);
                    break;
                case "2":
                    BaseUtils.toActivity(this, AskForLeaveActivity.class, intent);
                    break;
                case "3":
                    BaseUtils.toActivity(this, OutApplyActivity.class, intent);
                    break;
                case "4":
                    BaseUtils.toActivity(this, EvectionApplyActivity.class, intent);
                    break;
                case "5":
                    BaseUtils.toActivity(this, WorkOverTimeActivity.class, intent);
                    break;

            }
            finish();
        }
    }
}
